import React, { Component } from "react";
import { Card, Button, Table, Modal, message } from "antd";
import { formdateDate } from "../../util/datatutil";
import { reqUsers, reqAddOrUpdateUser, reqDeleteUser } from "../../api";
import Userform from "./userform";

class User extends Component {
  constructor(props) {
    super(props);
    this.state = {
      users: [], // 用户列表
      roles: [], //角色列表
      isShow: false, //控制弹框
    };
  }
  initColumns = () => {
    this.columns = [
      {
        title: "用户名",
        dataIndex: "username",
      },
      {
        title: "邮箱",
        dataIndex: "email",
      },
      {
        title: "电话",
        dataIndex: "phone",
      },
      {
        title: "注册时间",
        dataIndex: "create_time",
        render: formdateDate,
      },
      {
        title: "所属角色",
        dataIndex: "role_id",
        render: (role_id) => this.roleNames[role_id],
      },
      {
        title: "操作",
        render: (user) => {
          return (
            <span>
              <Button type="primary" onClick={() => this.updateUser(user)}>
                修改
              </Button>
              <Button type="primary" onClick={() => this.deleteUser(user)}>
                删除
              </Button>
            </span>
          );
        },
      },
    ];
  };
  initRoleNames = (roles) => {
    const roleNames = roles.reduce((pre, role) => {
      pre[role._id] = role.name;
      return pre;
    }, {});
    console.log(11, roleNames);
    this.roleNames = roleNames;
  };
  //获取用户列表
  getUsers = async () => {
    const result = await reqUsers();
    console.log(result);
    if (result.status === 0) {
      const { users, roles } = result.data;
      this.initRoleNames(roles);
      this.setState({
        users,
        roles,
      });
    }
  };
  //显示弹框
  showAdd = () => {
    this.user = null;
    this.setState({ isShow: true });
  };
  //弹出修改框
  updateUser = (user) => {
    this.user = user;
    this.setState({
      isShow: true,
    });
  };
  //添加用户
  addOrUpdateUser = async () => {
    this.setState({ isShow: false });
    const user = this.form.getFieldsValue();
    this.form.resetFields();
    if (this.user) {
      user._id = this.user._id;
    }
    const result = await reqAddOrUpdateUser(user);
    if (result.status === 0) {
      message.success(`${this.user ? "修改" : "添加"}用户成功`);
      this.getUsers();
    }
  };
  //删除用户
  deleteUser = (user) => {
    Modal.confirm({
      title: `确定删除${user.username}吗?`,
      onOk: async () => {
        const result = await reqDeleteUser(user._id);
        if (result.status === 0) {
          message.success("删除用户成功");
          this.getUsers();
        }
      },
    });
  };
  componentWillMount() {
    this.initColumns();
  }
  componentDidMount() {
    this.getUsers();
  }
  render() {
    const { users, isShow, roles } = this.state;
    const user = this.user || {};
    const title = (
      <Button type="primary" onClick={this.showAdd}>
        创建用户
      </Button>
    );
    return (
      <Card title={title}>
        <Table rowKey="_id" columns={this.columns} dataSource={users} />
        <Modal
          title={user._id ? "修改" : "添加"}
          visible={isShow}
          onOk={this.addOrUpdateUser}
          onCancel={() => {
            this.setState({ isShow: false });
          }}
        >
          <Userform
            user={user}
            roles={roles}
            setForm={(form) => {
              this.form = form;
            }}
          />
        </Modal>
      </Card>
    );
  }
}

export default User;
